package com.xingxin.config;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.support.SimpleTriggerContext;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录拦截器
 */

@Component
public class LoginInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

    //在业务处理器处理请求之前被调用。预处理，可以进行编码、安全控制、权限校验等处理
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object o) throws Exception {

        logger.info("==>LoginInterceptor--start--request path is:[{}]  uri is:[{}]",
                request.getServletPath(), request.getRequestURI());
        PrintWriter writer;
        //设置响应头
        this.addResponse(request,response);
        //从请求头获取token
        String token = request.getHeader("token");
        logger.info("==>LoginInterceptor--start--getHeader--token is {}",token);
        if (StringUtils.isBlank(token)) {
            writer = response.getWriter();
            writer.print("{\"code\":\"-1\",\"msg\":\"token is null\"}");
            writer.close();
            return false;
        }
        if(TokenTools.verify(token)) {
            return true;
        }
        writer = response.getWriter();
        writer.print("{\"code\":\"-1\",\"msg\":\"token is error\"}");
        writer.close();
        return false;
    }

    //在业务处理器处理请求执行完成后，生成视图之前执行。后处理
    // (调用了Service并返回ModelAndView，但未进行页面渲染），有机会修改ModelAndView
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) {

    }

    //在DispatcherServlet完全处理完请求后被调用，可用于清理资源等。返回处理（已经渲染了页面）
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {

    }

    /**
     * 设置响应头--解决跨域
     * @param request
     * @param response
     */
    private void addResponse(HttpServletRequest request, HttpServletResponse response){
        //设置响应头
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setHeader("x-frame-options", "SAMEORIGIN");
        // 不使用*，自动适配跨域域名，避免携带Cookie时失效
        String origin = request.getHeader("Origin");
        if (StringUtils.isNotBlank(origin)) {
            response.setHeader("Access-Control-Allow-Origin", origin);
        }
        // 自适应所有自定义头
        String headers = request.getHeader("Access-Control-Request-Headers");
        if (StringUtils.isNotBlank(headers)) {
            response.setHeader("Access-Control-Allow-Headers", headers);
            response.setHeader("Access-Control-Expose-Headers", headers);
        }
        // 允许跨域的请求方法类型
        response.setHeader("Access-Control-Allow-Methods", "*");
        // 预检命令（OPTIONS）缓存时间，单位：秒
        response.setHeader("Access-Control-Max-Age", "3600");
        // 明确许可客户端发送Cookie，不允许删除字段即可
        response.setHeader("Access-Control-Allow-Credentials", "true");
    }
}